<template>
  <!-- 事件代理：@click="navClick($event)" -->
  <div
    class="nav-bar"
    v-nav-current="{
      className: 'nav-item',
      activeClass: 'nav-current',
      curIdx,
    }"
    @click="navClick($event)"
  >
    <div class="scroll-wrapper">
      <div class="nav-wrapper" :style="`width: ${navData.length * 0.8}rem`">
        <!-- 写法一： -->
        <!-- :curIdx="curIdx" -->

        <!-- @navClick="navClick" -->
        <nav-item
          v-for="(item, index) of navData"
          :key="index"
          :item="item"
          :index="index"
        ></nav-item>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import { useStore } from "vuex";
import navData from "../../datas/nav";
import NavItem from "./Item.vue";

import { navCurrent } from "../../directives/index";
import getData from "../../services/index";

export default {
  name: "NavBar",
  components: {
    NavItem,
  },
  directives: {
    navCurrent,
  },
  setup() {
    //写法一:
    // const curIdx = ref(0);

    // const navClick = (index) => {
    //   //更改curIdx实现点击nav显示当前样式
    //   //click -> nav-item nav-current
    //   curIdx.value = index;
    // };

    //写法二：
    const curIdx = ref(0);
    const store = useStore();

    const navClick = (e) => {
      const className = e.target.className;

      if (className === "nav-item") {
        const tar = e.target,
          idx = tar.dataset.index,
          consName = tar.innerText;

        // console.log(idx);
        curIdx.value = idx;

        // console.log(consName);
        //金牛座

        //将拿到的nav名称保存到state里
        store.commit("setConsName", consName);

        //切换nav栏时需要重新获取后端数据
        getData(store);
      }
    };

    return {
      navData,
      curIdx,
      navClick,
    };
  },
};
</script>

<style lang="scss" scoped>
.nav-bar {
  position: fixed;
  top: 0.44rem;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 0.38rem;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  background-color: #fff;
  overflow: hidden;

  .scroll-wrapper {
    height: 0.46rem;
    overflow-x: auto;

    .nav-wrapper {
      display: flex;
      flex-direction: row;
      height: 0.42rem;
    }
  }
}
</style>